//配置axios的全局属性和基础路径
Vue.prototype.$http = axios;
//每次发送axios请求之前都会加上这个基础路径
axios.defaults.baseURL = "http://localhost:8080";


//1.axios前置拦截器：每次通过axios发送请求之前，让所有的请求都携带token
axios.interceptors.request.use(res => {
    //携带token
    let token = localStorage.getItem("token");
    if (token) {
        //将token设置到请求头携带到后端
        res.headers['token'] = token;
    }
    return res;
}, error => {
    Promise.reject(error);
})

//2.axios后置拦截器：后端处理完axios请求之后，处理响应的数据
//后置拦截器一定会比回调函数优先执行
axios.interceptors.response.use(res => {
    //后端响应的是没有登录的信息
    if (res.data.success === false && res.data.msg === "noLogin") {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        localStorage.removeItem("menus");
        localStorage.removeItem("permissions");
        //跳转到登陆页面
        location.href = "/login.html";
    }else if(res.data.success === false && res.data.msg === "timeout"){
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        localStorage.removeItem("menus");
        localStorage.removeItem("permissions");
        //跳转到登陆页面
        location.href = "/login.html";
    }
    return res;
}, error => {
    Promise.reject(error);
})

//静态资源拦截器
//获取请求路径
let url = location.href;

//获取请求地址
let path = url.substring(url.lastIndexOf("/"));
//console.log(path);// /callback.html?code=051fU00w3BS4603F7K0w3Y29Oj1fU00A&state=1
//不是受限资源，就判断有没有登录
if (path != "/login.html" && path != "/register.html"
    && url.indexOf("/binder.html") == -1 && url.indexOf("/callback.html") == -1){
    let logininfo = localStorage.getItem('logininfo');
    if (!logininfo){//没有登录跳转到登录页面
        location.href = "login.html";
    }
}


//将路径上的参数转化为json对象
function parseUrlParams2Obj(url){// /callback.html?code=111&state=1
    let obj = {};
    let params = url.substring(url.indexOf("?") + 1);// code=111&state=1
    let paramsArr = params.split("&");// [code=111,state=1]
    for (let i = 0;i < paramsArr.length; i++ ){
        let paramArr = paramsArr[i].split("="); //[code,111] or [state,1]
        obj[paramArr[0]] = paramArr[1];//解构表达式
    }
    return obj;
}
